package com.inspectortime.webapp.inspector;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.RealEstateAgent;
import com.inspectortime.domain.util.NameComparator;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;
import com.inspectortime.webapp.util.RequestPathUtils;

public class ViewReferringRealtorsController implements Controller {
	
	private Repository repository;
	
    public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		
		ModelAndView mv = new ModelAndView(RequestPathUtils.extractViewNameFromPath(request));
		Collection<RealEstateAgent> agents = company.getReferringAgents();
		
		if (agents != null) {
			List<RealEstateAgent> sortedAgents = new ArrayList<RealEstateAgent>(agents);
			sortByName(sortedAgents);
			mv.addObject("realtors", sortedAgents);
			
		} else {
			mv.addObject("realtors", Collections.EMPTY_LIST);
		}
        
        return mv;
	}
	
	private void sortByName(List<RealEstateAgent> agents) {
		Collections.sort(agents, new Comparator<RealEstateAgent>() {
	           public int compare(RealEstateAgent agent1, RealEstateAgent agent2) {
	        	   return new NameComparator().compare(agent1.getName(), agent2.getName());
	           }
	       });
	}
	
}
